package com.paic.custserv.web;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.paic.custserv.common.Constant;
import com.paic.custserv.common.enums.StatusEnum;

/**
 * ajax错误拦截器.
 */
public class AjaxErrorInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(AjaxErrorInterceptor.class);

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws IOException {
        if (Constant.AJAX_REQUEST_HEADER_VALUE.equals(request.getHeader(Constant.AJAX_REQUEST_HEADER_NAME))
                && ex != null) {
            String errorMessage = "后台报错，请联系系统管理员!";
            if (ex instanceof AccessDeniedException) {
                errorMessage = ex.getMessage();
            }
            byte[] data = String.format("{\"result\":\"error\",\"error\":\"%s\", \"errorCode\":%d}", errorMessage,
                    StatusEnum.fail).getBytes("utf-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setContentLength(data.length);
            OutputStream os = response.getOutputStream();
            LOG.warn(ex.getMessage(), ex);
            try {
                os.write(data);
            }
            finally {
                os.close();
            }
        }
    }

}
